  (async function(){
  const fs = require("fs");
  const http = require("http");
  const path = require("path");
  const log = require("./log.js");
  const config = require("./config.js")[process.env.RUN_CONF];
  // const db = require("./mysql.js");
  const db = require("./remote.js");
  const downloadDir = './download/';

  fs.existsSync(downloadDir) || fs.mkdirSync(downloadDir);
  const perDirDown =(o)=> {
    // log('开始分片下载'+count);
    if(!o.imgBuyhouse){
      log('没有购房证明，data:'+o,'error');
      return;
    }
    startDownloadTask(o.imgBuyhouse, downloadDir+o.id, `购房证明`);
    if(o.imgDaikuan){
      o.imgDaikuan.split(',').forEach((url,i)=>{
        startDownloadTask(url, downloadDir+o.id, `征信证明${i+1}`);
      });
    }
    if(o.imgIdfront1){
      startDownloadTask(o.imgIdfront1, downloadDir+o.id, `${o.name1}身份证正面`);
    }
    if(o.imgIdback1){
      startDownloadTask(o.imgIdback1, downloadDir+o.id, `${o.name1}身份证背面`);
    }
    if(o.imgIdfront2){
      startDownloadTask(o.imgIdfront2, downloadDir+o.id, `${o.name2}身份证正面`);
    }
    if(o.imgIdback2){
      startDownloadTask(o.imgIdback2, downloadDir+o.id, `${o.name2}身份证背面`);
    }
    if(o.imgIdfront3){
      startDownloadTask(o.imgIdfront3, downloadDir+o.id, `${o.name3}身份证正面`);
    }
    if(o.imgIdback3){
      startDownloadTask(o.imgIdback3, downloadDir+o.id, `${o.name3}身份证背面`);
    }
    return 1;
  }
  // const JSZip = require('jszip');
  // var zip = new JSZip();

  async function userList(){
    return await db.query();
  }
  async function userListMysql(){
    let sql =`select a.id,a.buyHouseNum,a.img_buyhouse imgBuyhouse,a.img_daikuan imgDaikuan,
    a.name1,a.img_idfront1 imgIdfront1,a.img_idback1 imgIdback1,
    a.name2,a.img_idfront2 imgIdfront2,a.img_idback2 imgIdback2,
    a.name3,a.img_idfront3 imgIdfront3,a.img_idback3 imgIdback3
     from bxa_user_${config.tt} a`;
    return await db.query(sql+" order by a.id ");
  }
  let isAllStart = false;
  const downMap={};
  function getHttpReqCallback(imgSrc, dirName, index) {
    var fileName = index + "." + path.basename(imgSrc).split(".")[1];
    var callback = function(res) {      
      log("request: " + dirName+ "/" +index + " return status: " + res.statusCode);
      var fileBuff = [];
      res.on('data', function (chunk) {
        var buffer = new Buffer(chunk);
        fileBuff.push(buffer);
      });
      res.on('end', function() {
        log("end downloading " +  dirName+"/" + index);
        var totalBuff = Buffer.concat(fileBuff);
        fs.appendFile(dirName + "/" + fileName, totalBuff, function(err){});
        delete downMap[imgSrc];
        if(Object.keys(downMap).length === 0){
          log("分片下载完成"+count++);
          if(!down.next().value){
            log("所有文件下载完成");
            process.exit(0);
          }
          else{
            log("开始分片下载"+count);
          }
        }
        // zip.file('test.txt', 'hello there');
        // zip.folder("images/img").file(fileName, totalBuff);
        // zip.generateAsync({type:"blob"}).then(function(content) {
        //     // see FileSaver.js
        //     saveAs(content, "example.zip");
        // });
      });
    };
    return callback;
  }
  var startDownloadTask = function(imgSrc, dirName, index) {
    log("start downloading " + dirName+"/" + index+":"+imgSrc);
    fs.existsSync(dirName) || fs.mkdirSync(dirName);
    // var fileName = index + "." + path.basename(imgSrc).split(".")[1];
    // if(fs.existsSync(dirName+"/"+fileName)){
    //   log(dirName+"/"+fileName+'已下载，跳过...');
    //   return ;
    // }
    downMap[imgSrc] = true;
    var req = http.request(imgSrc, getHttpReqCallback(imgSrc, dirName, index));
    req.setTimeout(60 * 1000, function() {
      log("reqeust " + dirName+"/" + index +" timeout, abort this reqeust",'error');
      req.abort();
    })
    req.on('error', function(e){
      log("request " + dirName+"/" + index+ " error, try again",'error');
      startDownloadTask(imgSrc, dirName, index);
    });
    req.end();
  }

  // urlList.forEach(function(item, index, array) {
  //   startDownloadTask(item, './', index);
  // })
  // const downList =async ()=>{
  //   return await userList();
  // }()
  const downList = await userList();
  log("开始下载，列表长度"+downList.length)
  var count =1;
  var downCount =0;
  function *perDown(){
    for(var i =0;i<downList.length;i++){
        if(fs.existsSync(downloadDir+downList[i].id)){
          log(downloadDir+downList[i].id +'已下载，跳过...');
          continue
        }
        downCount++;
        if(i%3 ===0){
          yield perDirDown(downList[i]);
        }
        else{
          perDirDown(downList[i]);
        }
    }
    // downList.forEach( *(o,i)=>{
    //   // if(!fs.existsSync(downloadDir+o.buyHouseNum)){
    //     // perDirDown(o);
    //   // }
    //   if(i%10 ===0){
    //     yield
    //   }
    // });
  }
  var down = perDown();
  down.next();
  if(downCount ===0){
    log("无下载任务");
    process.exit(0);
  }
  else{
    log("开始分片下载"+count);
  }
  // var count =1;
  // while(Object.keys(downMap).length === 0 ){
  //   log('开始分片下载'+(count++));
  //   if(!down.next().value){
  //       break;
  //   }
  // }
  isAllStart = true;

  // fs.writeFile('demo.zip', data, 'binary', function(){
  //     log('success');
  // });
 })()